#include "comdata.h"
#include <QDebug>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonParseError>
#include <QJsonObject>
#include <QProcess>
#include "../logs/printlog.h"
/*
send
{
"s":0 chaxun  1 kaishi  2 tingzhi 3 qvxiaso  6shijian
"t":"times"
}###
recv
{
"s":0 tingzhi 1 zhengzaiyunxin 2 jieshu 3 qvxiaso 4yunxingjiankong
"r":0 yunzhengdezhi
"n":0 jieguo
}###
*/

ComData::ComData(QObject *parent) : QObject(parent)
  , m_serialPort(NULL)
  , m_curentPortName("")
{

}

ComData::~ComData()
{

}

ComData *ComData::gestance()
{
    static ComData   comData;

    return  &comData;
}

void ComData::sendSerielInfor(QString infors)
{
    QJsonObject json1;
    json1.insert("s",1);
    json1.insert("r",infors.toDouble());
    json1.insert("n",0.0);
    QJsonDocument doc1(json1);
    QString logStr= typeid(this).name()+QString(" %1").arg( __func__) +" -- "+ QString("%1").arg( __LINE__)  +" contents ="+" infors=="+infors;
    PrintLog::gestance()->printInfor(logStr);
    if(m_serialPort != NULL){
        QString infora = doc1.toJson()+"###";
        qDebug()<<" Seriealport::sendSerielInfor infora=="<<infora;
        int lens =m_serialPort->write(infora.toUtf8());
        m_serialPort->flush();
        qDebug()<<" Seriealport::sendSerielInfor lens=="<<lens;
    }
    qDebug()<<" Seriealport::sendSerielInfor end";
}

void ComData::sendEndInfor(QString infors)
{
    QJsonObject json1;
    json1.insert("s",2);
    json1.insert("r",0.0);
    json1.insert("n",infors.toDouble());;
    QJsonDocument doc1(json1);
    QString logStr= typeid(this).name()+QString(" %1").arg( __func__) +" -- "+ QString("%1").arg( __LINE__)  +" contents ="+" infors=="+infors;
    PrintLog::gestance()->printInfor(logStr);
    if(m_serialPort != NULL){
        QString infora = doc1.toJson()+"###";
        qDebug()<<" Seriealport::sendEndInfor infora=="<<infora;
        int lens =m_serialPort->write(infora.toUtf8());
        m_serialPort->flush();
        qDebug()<<" Seriealport::sendEndInfor lens=="<<lens;
    }
    qDebug()<<" Seriealport::sendEndInfor end";
}

void ComData::sendStatusInfor(QString infors)
{
    QJsonObject json1;
    json1.insert("s",infors.toInt());
    json1.insert("r",0.0);
    json1.insert("n",0.0);;
    QJsonDocument doc1(json1);
    QString logStr= typeid(this).name()+QString(" %1").arg( __func__) +" -- "+ QString("%1").arg( __LINE__)  +" contents ="+" infors=="+infors;
    PrintLog::gestance()->printInfor(logStr);
    if(m_serialPort != NULL){
        QString infora = doc1.toJson()+"###";
        qDebug()<<" Seriealport::sendEndInfor infora=="<<infora;
        int lens =m_serialPort->write(infora.toUtf8());
        m_serialPort->flush();
        qDebug()<<" Seriealport::sendEndInfor lens=="<<lens;
    }
    qDebug()<<" Seriealport::sendEndInfor end";
}

void ComData::onAddSerielComInfor()
{
    QSerialPortInfo infors;
    bool isInit= false;
    foreach( const QSerialPortInfo &qspinfo,QSerialPortInfo::availablePorts() ){
        if(qspinfo.portName().contains("ttyUSB")){
            m_curentPortName = qspinfo.portName();
            infors = qspinfo;
            isInit= true;
            qDebug()<<"Seriealport::onAddSerielInfor infors=="<<infors.portName();
            break;
        }
    }
    if(isInit){
        if(m_serialPort != NULL ){
            disconnect(m_serialPort, SIGNAL(readyRead()), this, SLOT( onRecSerialData() ) );
            m_serialPort->close();
            delete  m_serialPort;
            m_serialPort = NULL;
        }
        m_currentInfor.clear();
        qDebug()<<"Seriealport::onAddSerielInfor isInit==";
        QString currenNme="/dev/"+infors.portName();
        qDebug()<<"Seriealport::onAddSerielInfor currenNme=="<<currenNme;
        QString logStr= typeid(this).name()+QString(" %1").arg( __func__) +" -- "+ QString("%1").arg( __LINE__)  +" contents ="+" currenNme=="+currenNme;
        PrintLog::gestance()->printInfor(logStr);
        m_serialPort = new QSerialPort();
        connect(m_serialPort, SIGNAL(readyRead()), this, SLOT( onRecSerialData() ) );
        m_serialPort->setPortName(currenNme);
        m_serialPort->setBaudRate(QSerialPort::Baud115200);
        m_serialPort->setParity(QSerialPort::NoParity);
        m_serialPort->setDataBits(QSerialPort::Data8);
        m_serialPort->setStopBits(QSerialPort::OneStop);
        m_serialPort->setFlowControl(QSerialPort::NoFlowControl);
        if (m_serialPort->open(QIODevice::ReadWrite)) {
            qDebug()<<"open success";
            logStr= typeid(this).name()+QString(" %1").arg( __func__) +" -- "+ QString("%1").arg( __LINE__)  +" contents ="+" open success";
            PrintLog::gestance()->printInfor(logStr);
        } else {
            qDebug()<<"open failed";
            logStr= typeid(this).name()+QString(" %1").arg( __func__) +" -- "+ QString("%1").arg( __LINE__)  +" contents ="+" open failed";
            PrintLog::gestance()->printInfor(logStr);
        }
    }

}

void ComData::onRemoveSerielComInfor()
{
    bool isInit= false;
    foreach( const QSerialPortInfo &qspinfo,QSerialPortInfo::availablePorts() ){
        if(m_curentPortName == qspinfo.portName()){


            isInit= true;
            break;
        }
    }

    if(!isInit){
        if(m_serialPort != NULL ){
            QString logStr= typeid(this).name()+QString(" %1").arg( __func__) +" -- "+ QString("%1").arg( __LINE__)  +" contents ="+" m_curentPortName=="+m_curentPortName;
            PrintLog::gestance()->printInfor(logStr);
            m_curentPortName ="";
            disconnect(m_serialPort, SIGNAL(readyRead()), this, SLOT( onRecSerialData() ) );
            m_serialPort->close();
            delete  m_serialPort;
            m_serialPort = NULL;
            m_currentInfor.clear();
        }
    }
}

void ComData::onRecSerialData()
{

    if(m_serialPort != NULL){
        QByteArray ba;
        ba = m_serialPort->readAll();
        if(ba.length() > 0){
            QString logStr= typeid(this).name()+QString(" %1").arg( __func__) +" -- "+ QString("%1").arg( __LINE__)  +" contents ="+" ba=="+ba;
            PrintLog::gestance()->printInfor(logStr);
            m_currentInfor += ba;
            if(m_currentInfor.contains("###")){
                QStringList lista =  m_currentInfor.split("###");
                for(int i = 0; i < lista.length() ;i++){
                    QString aStr = lista.at(i);
                    if(aStr.length() > 0){
                        QJsonParseError errors;
                        QJsonDocument doca =  QJsonDocument::fromJson(aStr.toUtf8() , &errors);
                        if(errors.error == QJsonParseError::NoError){
                            m_currentInfor.remove(aStr+"###");
                            QJsonObject object =  doca.object();
                            int status =  object.take("s").toInt();
                            if(status == 6){
                                QString times =     object.take("t").toString();
                                QString cmds = QString("sudo date --s=\"%1\"").arg(times);
                                QProcess::startDetached(cmds);

                            }else{
                                emit  sigCheckStatus(status);

                            }

                        }

                    }

                }

            }
        }

        // emit sigSerielInfor( ba);

        qDebug()<<"Seriealport::onRecSerialData ba =="<<ba.toHex();
    }
}
